package com.example.chatroom.contoller;

import com.example.chatroom.model.Result;
import com.example.chatroom.model.User;
import com.example.chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result<Boolean> getUserByName(String username, String password, HttpServletRequest request) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail(400,"用户名或者密码为空，请检查后重新登录",false);
        }
        User user = userService.getUserByName(username);
        if (user == null || user.getUserId() < 0) {
            return Result.fail(400,"用户不存在",false);
        }
        if (user.getPassword().equals(password)) {
            HttpSession session = request.getSession();
            user.setPassword("");
            session.setAttribute("userinfo",user);
            return Result.success(true);
        }else {
            return Result.fail(400,"密码错误",false);
        }
    }

    @RequestMapping("/registry")
    public Result<Boolean> registry(String reusername,String repassword,String rerepassword) {
        if (!StringUtils.hasLength(reusername) || !StringUtils.hasLength(repassword)
        || !StringUtils.hasLength(rerepassword)) {
            return Result.fail(400,"用户名或者密码、确认密码为空",false);
        }
        if (!repassword.equals(rerepassword)) {
            return Result.fail(400,"两次输入的密码不同，请确认后重新输入",false);
        }
        User user = userService.getUserByName(reusername);
        if (user != null) {
            return Result.fail(400,"用户已存在",false);
        }
        Integer ret = userService.registry(reusername,repassword);
        if (ret >= 1) {
            return Result.success(true);
        }else {
            return Result.fail(500,"注册失败，请联系管理员",false);
        }
    }
}
